from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
# Create your views here.
from users.models import Users
from users.utlis import check_verify_token
from .serializer import RegisterCreateUserSerializer
from .serializer import AddressSerializer

class RegisterUsernameView(APIView):
    """
   判断用户名是否重复
    1.让前端把用户名传递过来
    2.以get方式把用户名传递过来
    3.实现业务逻辑

    GET         users/usernames/username
    GET         users/usernames/(?P<username>/w{5,20})/count/

    """

    def get(self, request, username):
        # count = 0 没有
        # count = 1 注册过
        count = Users.objects.filter(username=username).count()

        # 组织数据
        context = {
            'username': username,
            'count': count,
        }

        return Response(context)


class RegisterMobilenameView(APIView):
    """
    验证手机号　我自己写的
    """

    def get(self, request, mobile):
        count = Users.objects.filter(mobile=mobile).count()
        context = {
            "count": count,
            "phone": mobile,

        }

        return Response(context)


class RegisterCreateUserView(APIView):
    """
    1.我们需要让前端把　用户名,密码,确认密码,手机号,短信验证码,是否同意协议　传过来
    2.后端接收参数,对参数进行校验
    3.数据入库
    4.返回响应


    """

    def post(self, request):
        # 1.接收参数
        data = request.data
        # 2.创建序列化器
        serializer = RegisterCreateUserSerializer(data=data)
        # 进行校验
        # raise_exception=True 如果有异常　则抛出异常,后边的代码不执行
        serializer.is_valid(raise_exception=True)
        # 数据入库
        serializer.save()

        return Response(serializer.data)


###############个人信息的邮箱####################


from rest_framework.permissions import IsAuthenticated


class UserCenterInfoView(APIView):
    """""
    1.必须是登陆用户 才可以访问该页面
    2.获取用户信息 直接返回就可以

    GET 方式

    """
    # 必须是登陆用户才可以访问该页面
    penrmission_classes = [IsAuthenticated]

    def get(self, request):
        # 我们采用的是 jwt_token 认证
        # 前端把token传递给我 我就知道 谁登陆了
        # request.user 就是认证登录的用户
        from .serializer import UserCenterInfoView
        user = request.user

        serializer = UserCenterInfoView(user)

        return Response(serializer.data)

        pass




# 邮件保存
from rest_framework.generics import UpdateAPIView
# class UserUpdateEmailView(APIView):
#
#     """
#     1.用户在点击设置的时候,输入邮箱,点击保存的时候,前段应该将邮件信息保存给后台
#     # 2.后台接收到邮件信息之后 需要进行校验
#     # 3.校验完成后对数据进行 保存
#     4.保存后 要发送一封激活邮件
#     # 5.返回响应
#
#     put         /users/emails/
#
#     """
#
#     permission_classes = [IsAuthenticated]
#
#     def put(self,request):
#
#         # 2.后台接收到邮件信息之后 需要进行校验
#         user = request.user
#
#         data = request.data
#
#         from .serializer import UserUpdateEmaiserializer
#
#         serializer = UserUpdateEmaiserializer(instance=user,data=data)
#
#         serializer.is_valid(raise_exception=True)
#
#         # 3.校验完成后对数据进行 保存
#         serializer.save()
#
#         # 5.返回响应
#         return Response(serializer.data)




"""
三级视图实现邮件保存
"""

from .serializer import UserUpdateEmaiserializer
from rest_framework.generics import UpdateAPIView

class UserUpdateEmailView(UpdateAPIView):

    permission_classes = [IsAuthenticated]
    serializer_class = UserUpdateEmaiserializer

    def get_object(self):

        return self.request.user


from rest_framework import status
class UserEmailActiveView(APIView):
    """

    GET     users/emails/verifications/?token=xxx
    """
    def get(self,request):
        # 1.获取token
        token = request.query_params.get('token')
        if token is None:
            return Response({'msg':'缺少参数'},status=status.HTTP_400_BAD_REQUEST)

        # 2.对token进行处理
        id = check_verify_token(token)

        if id is None:
            return Response({'msg':'token过期了'},status=status.HTTP_400_BAD_REQUEST)

        # 3.根据id查询用户
        try:
            user = Users.objects.get(id=id)
        except Users.DoesNotExist:
            return Response({'msg':'没有此用户'},status=status.HTTP_400_BAD_REQUEST)


        # 4.修改状态 返回响应
        user.email_active=True
        user.save()

        return Response({'msg':'ok'})



"""增加地址的类"""
class AddressView(APIView):
    """
    POST        users/addresses/
    """

    permission_classes = [IsAuthenticated]

    def post(self,request):
        """
        1.前端收集用户提交过来的数据,传递给后端
        2.接收数据,并对数据进行校验
        3.数据没有问题就入库
        4.返回响应
        :param request:
        :return:
        """
        data = request.data

        serializer = AddressSerializer(data=data,context={'request':request})

        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response(serializer.data)

    def get(self,request):
        pass

















